package com.Util;

import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;

/**
 * 	数据库连接工具类
 * @author hkw
 *
 */
public class JdbcUtil {

	private static String driver;
	private static String url;
	private static String username;
	private static String password;
	
	static {
		//创建properties 对象   用于加载jdbc的数据库连接的配置信息
		Properties prop = new Properties();
		//找到properties 配置文件 且将其转化为字节流
		InputStream in = JdbcUtil.class.getClassLoader()
				.getResourceAsStream("jdbc.properties");
		//加载properties 配置文件
		try {
			prop.load(in);
			//初始化数据库连接属性
			driver = prop.getProperty("driver");
			url = prop.getProperty("url");
			username = prop.getProperty("username");
			password = prop.getProperty("password");
			//加载驱动
			try {
				Class.forName(driver);
			} catch (ClassNotFoundException e) {
				e.printStackTrace();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	
	/**
	 * 	获取数据库连接
	 * @return
	 */
	public static Connection getConn() {
		Connection conn = null;
		try {
			conn = DriverManager.getConnection(url, username, password);
		} catch (SQLException e) {
			e.printStackTrace();
			System.out.println("获取数据库连接失败");
		}
		return conn;
	}
	
	/**
	 * 	释放资源
	 * @param conn
	 * @param prep
	 */
	public static void close(Connection conn,PreparedStatement prep) {
		if(prep != null) {
			try {
				prep.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		if(conn != null) {
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
	
	/**
	 * 	释放资源
	 * @param conn
	 * @param prep
	 * @param rs
	 */
	public static void close(Connection conn,PreparedStatement prep,ResultSet rs) {
		if(rs != null) {
			try {
				rs.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		close(conn, prep);
	}

	@Test
	public void test(){
		Connection conn = getConn();
		System.out.println(conn);
	}
}
